<template>
  <div class="commonTable" v-loading="loading">
    <div class="commonTable-title">
      <span>{{ chartName }}</span>
    </div>
    <div class="commonTable-date">
      <div class="commonTable-date-div">
        <!-- 日期 -->
        <p v-if="screenTime && screenTime.length != 0">
          <span class="left">{{ new Date(screenTime[0]).format("yyyy-MM-dd") }} ~ {{ new
            Date(screenTime[1]).format("yyyy-MM-dd") }}</span>
        </p>
        <!-- el-tooltip -->
        <p class="tooltip-p" v-if="screenTime && screenTime.length != 0">
          <el-tooltip content="筛选时段" placement="bottom" effect="light">
            <img class="right" :src="dateIcon" alt="">
          </el-tooltip>
        </p>
      </div>
      <!-- select -->
      <el-select v-if="options.length != 0" v-model="queryConditionVal" clearable placeholder="请选择"
        @change="handleChange">
        <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value">
        </el-option>
      </el-select>
    </div>
    <!-- elementUI table二次封装 -->
    <div class="commonTable-table" v-if="payloadData.data && payloadData.data.x.length != 0">
      <el-table :data="tableData" @sort-change="handleSortMethod" max-height="260px" style="width: 100%;height: 260px;"
        header-cell-class-name="headerCellClass">
        <template v-for="(item, index) in column" :key="index">
          <el-table-column :width="item.width ? item.width : 'auto'" :prop="item.prop"
            :align="item.align ? item.align : 'center'" :label="item.label" :sortable="sortable">
            <template #default="scope" v-if="item.isNested ? item.isNested : false">
              <el-table-column v-for="(value, key) in item.childrenColumn" :key="key"
                :width="value.width ? value.width : 'auto'" :prop="value.prop"
                :align="value.align ? value.align : 'center'" :label="value.label">
                <template #default="scope">
                  <slot v-if="value.slot" :name="value.prop" :row="scope.row"></slot>
                  <template v-else>
                    {{ scope.row[value.prop] }}
                  </template>
                </template>
              </el-table-column>
            </template>
            <template #default="scope" v-else>
              <slot v-if="item.slot" :name="item.prop" :row="scope.row"></slot>
              <template v-else>
                {{ scope.row[item.prop] }}
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <!-- <el-pagination 
        class="pagination"
        @current-change="handleCurrentChange"
        :current-page="pageVo.currentPage"
        :page-size="pageVo.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="pageVo.total">
      </el-pagination> -->
    </div>
    <!-- empty -->
    <el-empty v-else :image="emptyImg" description="暂无数据" :image-size="80" style="width: 100%;height: 272px;"></el-empty>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import dateIcon from '@/assets/dataCenter/dataB_dateIcon.png';
import emptyImg from '@/assets/dataCenter/dataB_empty.png';
// API
import {
  merchantReportQueryData,
  merchantReportQueryCondition
} from '@/api/dataCenter/dataBoard.js';
// utils
import { dateStrChangeTimeTamp } from './utils.js';
import { useTransitionFallthroughEmits } from "element-plus";

export default {
  name: 'CommonTable',
  props: {
    id: {
      type: String,
      default: () => {
        return null;
      }
    },
    chartName: {
      type: String,
      default: () => {
        return '';
      }
    },
    tableData: {
      type: Array,
      default: () => {
        return [
          {
            id: "1",
            name: "张三",
            sex: 0,
            age: 12,
            grade: 1,
            desc: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
          },
          {
            id: "2",
            name: "李四",
            sex: 0,
            age: 13,
            grade: 2,
            desc: "HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH"
          },
          {
            id: "3",
            name: "李丽",
            sex: 1,
            age: 13,
            grade: 2,
            desc: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
          }
        ];
      }
    },
    column: {
      type: Array,
      default: () => {
        return [
          {
            prop: "id",
            align: "",
            label: "ID",
            scopeStatus: true,
            width: "",
            minWidth: ""
          },
          {
            prop: "name",
            align: "",
            label: "姓名",
            scopeStatus: false,
            width: "",
            minWidth: ""
          },
          {
            prop: "sex",
            align: "",
            label: "性别",
            scopeStatus: true,
            width: "",
            minWidth: ""
          },
          {
            prop: "age",
            align: "",
            label: "年龄",
            scopeStatus: false,
            width: "",
            minWidth: ""
          },
          {
            prop: "grade",
            align: "",
            label: "年级",
            scopeStatus: true,
            width: "",
            minWidth: ""
          },
          {
            prop: "desc",
            align: "",
            label: "描述",
            scopeStatus: true,
            width: "",
            minWidth: ""
          }
        ];
      }
    }
  },
  inject: ['actId'],
  data() {
    return {
      loading: false,
      dateIcon,
      emptyImg,
      loading: false,
      data: {},
      payloadData: {},
      relativelyTimeDeal: null,
      column: [
        {
          prop: 'date',
          align: '',
          label: '日期',
          scopeStatus: false,
          width: "",
        }
      ],
      tableData: [],
      pageVo: {
        currentPage: 1,
        pageSize: 10,
        total: 100
      },
      queryConditionVal: '',
      queryConditionKey: '',
      options: [],
      sortable: false,
      sortVal: ''
    }
  },
  watch: {
    screenTime: {
      handler(val) {
        this.merchantReportQueryDataApi();
      },
      deep: true
    },
    organizationId: {
      handler(val) {
      },
      deep: true
    }
  },
  mounted() {
    console.log('this.id+++++++', this.id)
    if (this.id === 'mallOrderDetailProvider') {
      this.sortable = true;
    }
    this.merchantReportQueryConditionApi();
  },
  methods: {
    // 排序
    handleSortMethod(val) {
      let sort = val.order; // "ascending"正序 "descending"倒序
      let row = val.column.label;
      if (row === '提交订单数') {
        if (sort === 'ascending') {
          this.sortVal = 'submitOrderAsc';
        } else {
          this.sortVal = 'submitOrderDesc';
        }
      }
      if (row === '完成订单数') {
        if (sort === 'ascending') {
          this.sortVal = 'completeOrderAsc';
        } else {
          this.sortVal = 'completeOrderDesc';
        }
      }
      if (row === '提交订单人数') {
        if (sort === 'ascending') {
          this.sortVal = 'submitOrderUserNumAsc';
        } else {
          this.sortVal = 'submitOrderUserNumDesc';
        }
      }
      if (row === '支付订单人数') {
        if (sort === 'ascending') {
          this.sortVal = 'payOrderUserNumAsc';
        } else {
          this.sortVal = 'payOrderUserNumDesc';
        }
      }
      if (row === '支付转化率') {
        if (sort === 'ascending') {
          this.sortVal = 'payConversionRateAsc';
        } else {
          this.sortVal = 'payConversionRateDesc';
        }
      }
      if (row === '申请退款订单数') {
        if (sort === 'ascending') {
          this.sortVal = 'submitRefundOrderNumAsc';
        } else {
          this.sortVal = 'submitRefundOrderNumDesc';
        }
      }
      if (row === '退款完成订单数') {
        if (sort === 'ascending') {
          this.sortVal = 'completeRefundOrderNumAsc';
        } else {
          this.sortVal = 'completeRefundOrderNumDesc';
        }
      }
      if (row === '交易金额(元)') {
        if (sort === 'ascending') {
          this.sortVal = 'payAmountAsc';
        } else {
          this.sortVal = 'payAmountDesc';
        }
      }
      if (row === '交易积分') {
        if (sort === 'ascending') {
          this.sortVal = 'payCurrencyAsc';
        } else {
          this.sortVal = 'payCurrencyDesc';
        }
      }
      this.merchantReportQueryDataApi();
    },
    // 导出
    exportExcel(excelName) {
      try {
        const $e = this.$refs['report-table'].$el
        let $table = $e.querySelector('.el-table__fixed')
        if (!$table) {
          $table = $e
        }

        const wb = XLSX.utils.table_to_book($table, { raw: true })
        const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          `${excelName}.xlsx`,
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }
    },
    handleChange(val) {
      this.merchantReportQueryDataApi();
    },
    // 获取条件切换接口
    async merchantReportQueryConditionApi() {
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let res = await merchantReportQueryCondition({
        startTime,
        endTime,
        chartType: 2,
        toIndex: 10,
        beanName: this.id,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId: this.actId ?? undefined
      })
      this.options = []
      if (res.code === 200) {
        if (res.payload.length != 0) {
          res.payload.forEach(item => {
            this.options.push(...item.options)
          })
          this.queryConditionVal = this.options[0].value || '';
          this.queryConditionKey = res.payload[0].key || '';

          let obj = {
           [`${this.id}Key`]:this.queryConditionVal
          }
          const data=store.state.user.queryConditionObj
          store.commit('SETQUERYCONDITIONOBJ', {...obj,...data})
        }
        this.merchantReportQueryDataApi();
      }
    },
    // 获取报表数据
    async merchantReportQueryDataApi() {
      this.loading = true;
      // screenTime为菜单筛选时间
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let paramStr = {
        startTime,
        endTime,
        chartType: 2,
        toIndex: null,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        sort: this.sortVal,
        actId: this.actId ?? undefined
      }
      paramStr[this.queryConditionKey] = this.queryConditionVal;
      paramStr = JSON.stringify(paramStr);
      let res = await merchantReportQueryData({
        beanName: this.id,
        param: paramStr,
      })
      if (res.code === 200) {
        this.payloadData = res.payload;
        this.capsulationDealData()
      }
      this.loading = false;
    },
    // 处理数据
    capsulationDealData(currentIndex) {
      if (Object.keys(this.payloadData).length === 0) return false;
      let dataValue = this.payloadData.data;
      let column = [];
      dataValue.x.forEach((item, index) => {
        let obj = {
          prop: "",
          align: "",
          label: "",
          scopeStatus: true,
          width: "",
          minWidth: ""
        }
        obj.prop = item + index;
        obj.label = item;
        column.push(obj);
      })
      let tableData = [];

      dataValue.y.forEach((val1, key1) => {
        let obj = {};
        val1.forEach((val2, key2) => {
          dataValue.x.forEach((item, index) => {
            if (key2 === index) {
              obj[item + index] = val2.val;
            }
          })
        })
        tableData.push(obj);
      })
      console.log('column', column)
      console.log('tableData', tableData)
      this.column = column;
      this.tableData = tableData;
    },
    // 切换页数
    handleCurrentChange(val) {
      this.pageVo.currentPage = val;
      // 更新数据
      this.merchantReportQueryDataApi();
    }
  },
  computed: {
    screenTime() {
      return store.state.user.screenTime;
    },
    organizationId() {
      return store.state.insId.insId;
    }
  }
}
</script>

<style lang="scss" scoped>
.commonTable {
  width: 100%;
  height: 100%;

  &-title {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    span {
      color: #252934;
      height: 24px;
      // width: 112px;
      font-family: PingFangSC-Medium;
      font-size: 16px;
      line-height: 24px;
      cursor: pointer;
    }
  }

  &-date {
    width: 100%;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 34px;

    &-div {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .left {
      font-size: 12px;
      color: #6b798e;
    }

    .right {
      margin-left: 18px;
    }

    .tooltip-p {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  &-table {
    width: 100%;
    height: 272px;
  }
}
</style>

<style lang="scss" scoped>
.commonTable {
  position: relative;

  .pagination {
    position: absolute;
    right: 0;
    bottom: 0;
    height: 24px;
    padding: 0;
  }

  :deep(.el-pagination__total) {
    display: none;
  }

  :deep(.el-pagination__jump) {
    display: none;
  }

  :deep(.el-pager li.is-active) {
    font-weight: 900;
  }
}
</style>